//
//  MTRefreshPromptTool.swift
//  PPKit
//
//  Created by iosdevmac201 on 2020/9/14.
//  Copyright © 2020 scoresdata.net. All rights reserved.
//

import UIKit

/**⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️调用了结束刷新方法之后再调用状态显示栏
 * self.tableView.showRefreshTip(title: "加载成功")
 * ⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️
 */

private let MTRefreshTipViewHeight = 30.scale

extension UITableView {
    
    /// 显示刷新小提示
    /// - Parameter title: 显示内容
    func showRefreshTip(title:String) {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
            self.layer.transform = CATransform3DMakeTranslation(0, MTRefreshTipViewHeight, 0)
            let resuView = MTRefreshTipView(title: title)
            self.viewcontroller()?.view.addSubview(resuView)
            resuView.show()
            DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                resuView.hide(table: self)
            }
        }
    }
}

/// 刷新提示组件
class MTRefreshTipView: UIView {
    let titleLabel = UILabel(12.scale, weight: .regular, textColor: .white, align: .center)
    let backView = UIView()
    
    convenience init(title:String) {
        self.init()
        
        backgroundColor = pp_color(.CFFFFFF)
        frame = CGRect(x: 0, y: 0, width: pp_screen_width, height: MTRefreshTipViewHeight)
        
        titleLabel.alpha = 0.5
        titleLabel.text = title
        let labelWidth = min(title.autoWidth(font: titleLabel.font) + 100.scale, pp_screen_width / 3 * 2)
        
        backView.alpha = 0.5
        backView.backgroundColor = pp_color(.C159F48)
        addSubview(backView)
        backView.frame = CGRect(x: (pp_screen_width - labelWidth)/2, y: 0, width: labelWidth, height: MTRefreshTipViewHeight)
        
        addSubview(titleLabel)
        titleLabel.frame = self.frame
    }
    
    func show() {
        UIView.animate(withDuration: 0.2) {
            self.titleLabel.alpha = 1
            self.backView.alpha = 1
            self.backView.left = 0
            self.backView.width = pp_screen_width
        }
    }
    
    @objc func hide(table:UITableView) {
        UIView.animate(withDuration: 0.25, animations: {
            table.layer.transform = CATransform3DIdentity
            self.layer.transform = CATransform3DMakeTranslation(0, -MTRefreshTipViewHeight, 0)
        }) { (ani) in
            self.removeFromSuperview()
        }
    }
}
